package com.inch.web.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyInterceptor implements HandlerInterceptor {
    //before handler
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("interceptor before");
        HttpSession session = request.getSession();
        if(session.getAttribute("login")!=null){
            boolean login = (boolean) session.getAttribute("login");
            if(login){
                //return true means let handler run
                //false means not
                return true;
            } else {
                //redirect before intercept
                response.sendRedirect("/jsp/loginService.jsp");
                return false;
            }
        }
        response.sendRedirect("/jsp/loginService.jsp");
        return false;
    }

    //before response
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("interceptor post");
    }

    //after response and the view is showed
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("interceptor after");
    }
}
